package com.cjh.wechat.upload.controller;

import java.io.File;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.cjh.wechat.commom.util.DateUtil;
import com.cjh.wechat.commom.util.JSONUtil;
import com.cjh.wechat.upload.vo.ResponseVo;
import com.cjh.wechat.upload.vo.UploadFileVo;
import com.cjh.wechat.upload.vo.UploadImgVo;
import net.coobird.thumbnailator.Thumbnails;

@Controller
@RequestMapping("/upload")
public class UploadController
{
    private final String UPLOAD_URL  = "http://localhost/upload";
    private final String UPLOAD_PATH = "D:\\Software\\tomcat8.0\\upload";
    
    @ResponseBody
    @RequestMapping(value = "/uploadAudio", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    private String uploadAudio(@RequestParam MultipartFile file)
    {
        try
        {
            String randomName = UUID.randomUUID().toString().replace("-", "");
            String randomFileName = randomName + ".wav";
            // 生成存储路径
            String savePath = getAbsolutePath(randomFileName);
            // 存储
            File newFile = new File(savePath);
            uploadFile(file, newFile);
            return buildResponseVo(UPLOAD_URL + "/" + DateUtil.getDate() + "/" + randomFileName);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return buildErrorVo("上传失败,原因:" + e.getMessage());
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    private String uploadImg(@RequestParam MultipartFile file)
    {
        try
        {
            // 校验
            judgeImgFormat(file);
            // 生成存储文件名
            String randomName = UUID.randomUUID().toString().replace("-", "");
            String randomFileName = getRandomFileName(file, randomName);
            // 生成存储路径
            String savePath = getAbsolutePath(randomFileName);
            // 存储
            File newFile = new File(savePath);
            uploadFile(file, newFile);
            // 对图片进行压缩处理
            Thumbnails.of(savePath).size(1024, 768).toFile(newFile);
            Thumbnails.of(savePath).scale(1f).outputQuality(0.25f).toFile(newFile);
            return buildResponseVo(UPLOAD_URL + "/" + DateUtil.getDate() + "/" + randomFileName);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return buildErrorVo("上传失败,原因:" + e.getMessage());
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    private String uploadFile(@RequestParam MultipartFile file)
    {
        try
        {
            // 校验
            judgeFileFormat(file);
            // 生成存储文件名
            String randomName = UUID.randomUUID().toString().replace("-", "");
            String randomFileName = getRandomFileName(file, randomName);
            // 生成存储路径
            String savePath = getAbsolutePath(randomFileName);
            // 存储
            File newFile = new File(savePath);
            uploadFile(file, newFile);
            return buildResponseVo(UPLOAD_URL + "/" + DateUtil.getDate() + "/" + randomFileName, //
                    file.getOriginalFilename());
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return buildErrorVo("上传失败,原因:" + e.getMessage());
        }
    }
    
    // 上传文件，如果对应日期的文件夹没有则生成
    private void uploadFile(MultipartFile file, File newFile) throws Exception
    {
        if (!newFile.getParentFile().exists())
        {
            newFile.getParentFile().mkdirs();
        }
        file.transferTo(newFile);
    }
    
    // 生成文件存储的路径
    private String getAbsolutePath(String randomFileName)
    {
        // 根据日期划分文件夹
        String date = DateUtil.getDate();
        // 项目绝对路径
        String path = UPLOAD_PATH + "/" + date + "/" + randomFileName;
        return path;
    }
    
    // 获取存储的文件名
    private String getRandomFileName(MultipartFile file, String randomName)
    {
        // 获取上传文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 拼装成存储文件名
        String fileName = randomName + "." + fileType;
        return fileName;
    }
    
    private String buildResponseVo(String src)
    {
        ResponseVo responseVo = new ResponseVo();
        UploadImgVo uploadImgVo = new UploadImgVo();
        uploadImgVo.setSrc(src);
        responseVo.setCode(0);
        responseVo.setData(uploadImgVo);
        responseVo.setMsg("");
        String s = JSONUtil.objToJson(responseVo);
        return s;
    }
    
    // 判断图片规范
    private void judgeImgFormat(MultipartFile file) throws Exception
    {
        if (file == null)
        {
            throw new Exception("图片不能为空");
        }
        else if (file.getSize() >= 10 * 1024 * 1024)
        {
            throw new Exception("图片不能大于10M");
        }
    }
    
    // 判断文件规范
    private void judgeFileFormat(MultipartFile file) throws Exception
    {
        if (file == null)
        {
            throw new Exception("文件不能为空");
        }
        
        if (file.getSize() >= 200 * 1024 * 1024)
        {
            throw new Exception("文件不能大于200M");
        }
    }
    
    private String buildResponseVo(String src, String fileName)
    {
        ResponseVo responseVo = new ResponseVo();
        UploadFileVo uploadFileVo = new UploadFileVo();
        uploadFileVo.setSrc(src);
        uploadFileVo.setName(fileName);
        responseVo.setCode(0);
        responseVo.setData(uploadFileVo);
        responseVo.setMsg("");
        String s = JSONUtil.objToJson(responseVo);
        System.out.println(s);
        return s;
    }
    
    private String buildErrorVo(String message)
    {
        ResponseVo responseVo = new ResponseVo();
        responseVo.setCode(1);
        responseVo.setMsg(message);
        String s = JSONUtil.objToJson(responseVo);
        return s;
    }
}
